package com.zonski.jbots.desktop.client;

import java.awt.*;

import java.util.Vector;

import com.zonski.jbots.engine.Layer;
import com.zonski.jbots.engine.Room;
import com.zonski.jbots.engine.Entity;
import com.zonski.jbots.engine.QuickVector;


public final class RoomRenderer
{
    private EntityRendererFactory entityRendererFactory;
    private TileRenderer tileRenderer;

    public RoomRenderer(EntityRendererFactory entityRendererFactory, TileRenderer tileRenderer)
    {
        this.entityRendererFactory = entityRendererFactory;
        this.tileRenderer = tileRenderer;
    }

    public final EntityRendererFactory getEntityRendererFactory()
    {
        return this.entityRendererFactory;
    }

    public final TileRenderer getTileRenderer()
    {
        return this.tileRenderer;
    }

    public final void render(Graphics g, Room room)
    {
        int tileSize = room.getTileSize();

        for(int i=0; i<room.getNumberOfTilesAcross(); i++)
        {
            for(int j=0; j<room.getNumberOfTilesDown(); j++)
            {
                int tileId = room.getTileType(i, j);
                this.tileRenderer.render(g, tileId, i*tileSize, j*tileSize, 
                        tileSize, tileSize);
            }
        }

        QuickVector layers = room.getLayers();
        try
        {
            for(int i=layers.size(); i>0; )
            {
                i--;
                Layer layer = (Layer)layers.elementAt(i);
                QuickVector entities = layer.getEntities();
                for(int j=entities.size(); j>0; )
                {
                    j--;
                    Entity entity = (Entity)entities.elementAt(j);
                    EntityRenderer renderer = (EntityRenderer)entity.renderer;
                    if(renderer == null)
                    {
                        renderer = this.entityRendererFactory.getRenderer(entity);
                        entity.renderer = renderer;
                    }
                    renderer.render(g, entity);
                }
            }
        }catch(Exception ex){
            // catch array index out of bounds exceptions
            // TODO : log this or something equally fast instead
            //System.err.println("error rendering : "+ex);
            ex.printStackTrace();
        }
    }
}
